package com.zbkj.crmeb.order.channel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.crmeb.core.common.CommonResult;
import com.utils.EuropeUtil;
import com.utils.STAXUtil;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.request.EuropeOrderRequest;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.PurchaseOrder;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;

import cn.hutool.core.codec.Base64;

@Service("europeStoreOrderService")
public class EuropeStoreOrderServiceImpl extends AbstractStoreOrderService {
    private static Logger logger = LoggerFactory.getLogger(TmallStoreOrderServiceImpl.class);

    @Autowired
    EuropeUtil europeUtil;
    @Value("${europe.url}")
    private String europeUrl;
    @Value("${europe.username}")
    private String europeUsername;
    @Value("${europe.password}")
    private String europePassword;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    StoreOrderFactory storeOrderFactory;

    //@Async("taskExecutor")
    @Override
    public CommonResult addChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        EuropeOrderRequest request = getRequest(storeOrder,orderInfoVoList);
        String sendMsg =  EuropeUtil.getSendMsg(getBodyXml(storeOrder.getOrderId() ,request));

        String respXml = null;
        try {
            logger.info("---------------请求欧洲创建订单, 请求参数xml: {} ---------------", sendMsg);
            String auth = Base64.encode((europeUsername + ":" + europePassword).getBytes());
            respXml = europeUtil.getEuropeXmlNew(auth, europeUrl, sendMsg);
            logger.info("---------------请求欧洲创建订单, 返回参数xml: {} ---------------", respXml);
            if(StringUtils.isBlank(respXml)){
                return null;
            }
            String result = STAXUtil.getEuropResultStr(respXml, "CreateNewOrder");
            if("Success".equals(result)){
                if(storeOrder.getPushStatus()!=2){
                	//新增采购单
                	storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.EUROPE.getCode());
                	//新增采购商品
                	storeOrderFactory.insertPurchaseGoods(orderInfoVoList, storeOrder, true, result, null, false);
            		StoreOrder storeOrderUpdate = new StoreOrder();
            		storeOrderUpdate.setId(storeOrder.getId());
            		storeOrderUpdate.setPushStatus(1);
            		storeOrderUpdate.setPushMessage(storeOrder.getPushMessage()+" 欧洲推送:"+result);
                    storeOrderDao.updateById(storeOrderUpdate);
                    return CommonResult.success();
                }
            }

        	//新增采购单
        	storeOrderFactory.insertPurchaseOrder(storeOrder, false, PurchaseOrderChannelTypeEnum.EUROPE.getCode());
        	//新增采购商品
        	storeOrderFactory.insertPurchaseGoods(orderInfoVoList, storeOrder, false, result, null, false);
        } catch (Exception e) {
            logger.info("请求欧洲创建订单失败,---------------",e);
        }
		StoreOrder storeOrderUpdate = new StoreOrder();
		storeOrderUpdate.setId(storeOrder.getId());
		storeOrderUpdate.setPushStatus(2);
		storeOrderUpdate.setPushMessage(storeOrder.getPushMessage()+" 欧洲推送失败");
        storeOrderDao.updateById(storeOrderUpdate);
        
        return CommonResult.failed(respXml);
    }

    @Override
    public CommonResult cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        return null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        return null;
    }

    private EuropeOrderRequest getRequest(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        EuropeOrderRequest request = new EuropeOrderRequest();
        EuropeOrderRequest.BuyerInfo buyerInfo = new EuropeOrderRequest.BuyerInfo();
        if(9 != storeOrder.getSource()) {
            storeOrder.setPushOrderNo(orderInfoVoList.get(0).getChildOrderNumber());
        }
        request.setOrderId(storeOrder.getPushOrderNo());
//        request.setOrderId(storeOrder.getOrderId());
        buyerInfo.setName(storeOrder.getRealName());
        buyerInfo.setAddress(storeOrder.getUserAddress());
        buyerInfo.setCorriere("");
        buyerInfo.setNotes("");
        buyerInfo.setZipcode("");
        request.setBuyerInfo(buyerInfo);
        List<EuropeOrderRequest.Goods> goodsList = new ArrayList<EuropeOrderRequest.Goods>();
        for(StoreOrderInfoVo info : orderInfoVoList){
            EuropeOrderRequest.Goods goods = new EuropeOrderRequest.Goods();
            String barCode = info.getInfo().getProductInfo().getBarCode();
            goods.setId(barCode.substring(4, barCode.length()));
            goods.setPrice(info.getInfo().getSourceCostPrice().divide(new BigDecimal("8")).toString());
            goods.setQty(info.getInfo().getCartNum().toString());
            String[] sukArr = info.getInfo().getProductInfo().getAttrInfo().getSuk().split(",");
            if(sukArr.length >1 ){
                goods.setSize(sukArr[1]);
            }else {
                goods.setSize(sukArr[0]);
            }
            goodsList.add(goods);
        }
        request.setGoodsList(goodsList);
        return request;
    }


    private String getBodyXml(String orderId, EuropeOrderRequest request){
        String startXml = "<tem:CreateNewOrder><tem:orderID>"+orderId+"</tem:orderID>";
        String buyerInfoXml ="<tem:buyerInfo><![CDATA[<BuyerInfo><Name>"+request.getBuyerInfo().getName()+"</Name><Address>"+request.getBuyerInfo().getAddress()+"</Address><zipcode>"+request.getBuyerInfo().getZipcode()+"</zipcode><Corriere>"+request.getBuyerInfo().getCorriere()+"</Corriere><Notes>"+request.getBuyerInfo().getNotes()+"</Notes></BuyerInfo>]]></tem:buyerInfo>";
        String goodsListXml = getGoodsListXml(request.getGoodsList());
        String endXml = "</tem:CreateNewOrder>";
        return startXml+buyerInfoXml+goodsListXml+endXml;
    }

    private String getGoodsListXml(List<EuropeOrderRequest.Goods> goodsList){
        String goodsListStrartXml = "<tem:goodsList><![CDATA[<GoodsList>";
        StringBuffer sb = new StringBuffer();
        if(null!=goodsList && goodsList.size()>0){
            for(EuropeOrderRequest.Goods goods : goodsList){
               String goodsXml = "<Good><ID>"+goods.getId()+"</ID><Size>"+goods.getSize()+"</Size><Qty>"+goods.getQty()+"</Qty><Price>"+goods.getPrice()+"</Price></Good>";
                sb = sb.append(goodsXml);
            }
        }
        String goodsListEndXml ="</GoodsList>]]></tem:goodsList>";
        return goodsListStrartXml+sb.toString()+goodsListEndXml;
    }

    public String getEuropeXml(String username, String password, String europeUrl, String sendMsg) throws IOException {
        int count = 1;
        while (true) {
            if(count >= 5) {
                return null;
            }
            String login = username + ":" + password;
            String encoding = Base64.encode(login.getBytes());
            InputStreamReader isr = null;
            BufferedReader inReader = null;
            StringBuffer result = null;
            OutputStream outObject = null;
            try {
                URL url = new URL(europeUrl);
                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                // 设置HTTP请求相关信息
                //设置超时
                httpConn.setConnectTimeout(120 * 1000);
                httpConn.setReadTimeout(120 * 1000);
                httpConn.setRequestProperty("Content-Length", String.valueOf(sendMsg.getBytes().length));
                httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
                httpConn.setRequestMethod("POST");
                httpConn.setDoOutput(true);
                httpConn.setDoInput(true);
                httpConn.setUseCaches(false);
                httpConn.setRequestProperty("Content-Type", "text/xml");
                httpConn.setRequestProperty("Authorization", "Basic " + encoding);
                // 进行HTTP请求
                outObject = httpConn.getOutputStream();
                outObject.write(sendMsg.getBytes());
                if (200 != (httpConn.getResponseCode())) {
                    // 关闭输出流
                    if (outObject != null) {
                        outObject.close();
                    }
                    count ++;
                    //返回数据异常继续请求
                    continue;
                }
                // 获取HTTP响应数据
                isr = new InputStreamReader(httpConn.getInputStream(), "utf-8");
                inReader = new BufferedReader(isr);
                result = new StringBuffer();
                String inputLine;
                while ((inputLine = inReader.readLine()) != null) {
                    result.append(inputLine);
                }
                return result.toString();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            } finally {
                // 关闭输入流
                if (inReader != null) {
                    inReader.close();
                }
                if (isr != null) {
                    isr.close();
                }
                // 关闭输出流
                if (outObject != null) {
                    outObject.close();
                }
            }
        }
    }

    private void setAddress(StoreOrder storeOrder,List<StoreOrderInfoVo> orderInfoVoList,PurchaseOrder order){
        StoreOrderInfoVo info = orderInfoVoList.get(0);
        Integer tempId = info.getInfo().getProductInfo().getTempId();
        //收货地大陆
        if(AreaTypeEnum.getTypeByCode(storeOrder.getAreaType()).equals(AreaTypeEnum.CN)){
            if(StockAreaTempEnum.getByTempId(tempId).equals(StockAreaTempEnum.HK) ||
                    StockAreaTempEnum.getByTempId(tempId).equals(StockAreaTempEnum.EUR)){
                order.setRegion("中国");
                order.setProvince("香港");
                order.setCity("东区");
                order.setDistrict("柴灣豐業街");
                order.setAddress("4 號志同昌工業大廈 4 字樓 B 室");
                order.setConsignee("杨少峰");
                order.setMobile("90541984");
            }else {
                order.setConsignee(storeOrder.getRealName());
                order.setMobile(storeOrder.getUserPhone());
                order.setRegion(AreaTypeEnum.getTypeByCode(storeOrder.getAreaType()).getTypeName());
                order.setProvince(storeOrder.getProvince());
                order.setCity(storeOrder.getCity());
                order.setDistrict(storeOrder.getDistrict());
                order.setAddress(storeOrder.getDetail());
            }
            //收货地香港
        }else if(AreaTypeEnum.getTypeByCode(storeOrder.getAreaType()).equals(AreaTypeEnum.HK)){
            if(StockAreaTempEnum.getByTempId(tempId).equals(StockAreaTempEnum.HK) || StockAreaTempEnum.getByTempId(tempId).equals(StockAreaTempEnum.EUR)){
                order.setRegion("中国香港");
                order.setProvince("香港");
                order.setCity("东区");
                order.setDistrict("柴灣豐業街");
                order.setAddress("4 號志同昌工業大廈 4 字樓 B 室");
                order.setConsignee("杨少峰");
                order.setMobile("90541984");
            }else{
                order.setConsignee(storeOrder.getRealName());
                order.setMobile(storeOrder.getUserPhone());
                order.setRegion(AreaTypeEnum.getTypeByCode(storeOrder.getAreaType()).getTypeName());
                order.setProvince(storeOrder.getProvince());
                order.setCity(storeOrder.getCity());
                order.setDistrict(storeOrder.getDistrict());
                order.setAddress(storeOrder.getDetail());
            }
        }else {
            order.setConsignee(storeOrder.getRealName());
            order.setMobile(storeOrder.getUserPhone());
            order.setRegion(AreaTypeEnum.getTypeByCode(storeOrder.getAreaType()).getTypeName());
            order.setProvince(storeOrder.getProvince());
            order.setCity(storeOrder.getCity());
            order.setDistrict(storeOrder.getDistrict());
            order.setAddress(storeOrder.getDetail());
        }
    }
}
